package cn.lsnu.heritage.controller;

import cn.lsnu.heritage.common.Result;
import cn.lsnu.heritage.model.dto.UserloginDto;
import cn.lsnu.heritage.model.domain.User;
import cn.lsnu.heritage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
    /**
     * 登录
     *
     * @param loginUser 登录用户
     * @return {@link Result}
     */
    @PostMapping("/login")
    public Result login(@RequestBody User loginUser){
     String username = loginUser.getUsername();
     String password = loginUser.getPassword();
    try {
        UserloginDto login = userService.login(username, password);
        if (login!=null) {
           return Result.success(login) ;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Result.error("60000","失败");
    }
    return Result.error("40000","用户名或密码错误");
    }

    /**
     * 保存/修改用户
     *
     * @param user 用户
     * @return {@link Result}
     */
    @PostMapping("/saveUser")
    public Result saveUser(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        String name = user.getName();
        String address = user.getAddress();
        String phone = user.getPhone();
        Integer role = user.getRole();
        Integer age = user.getAge();
        if(userService.saveOrUpdate(user.getUsername())){
            try {
                userService.saveUser(username,password,name,address,phone,age,role);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("40000","保存失败");
            }
            return Result.success("保存成功");
        }else{
            try {
                userService.updateUser(username,password,name,address,phone,age,role);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("40000","修改失败");
            }
            return Result.success("修改成功");
        }


    }


}
